package vip.manda.framework.data.repository;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.lang.Assert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.ibatis.type.TypeAliasRegistry;
import vip.manda.framework.data.DataBaseSource;

import javax.sql.DataSource;
import java.util.Set;

/**
 * @author hongda.li 2022-04-02 14:34
 * Mybatis构造器
 */
public class MybatisBuilder {
    private static SqlSessionFactory FACTORY;

    private MybatisBuilder() {
    }

    public static SqlSession buildSession() {
        Assert.notNull(FACTORY, "MybatisBuilder hasn't been initialized");
        return FACTORY.openSession();
    }

    public static SqlSession buildSession(boolean autoCommit){
        Assert.notNull(FACTORY, "MybatisBuilder hasn't been initialized");
        return FACTORY.openSession(autoCommit);
    }

    /**
     * 初始化Mybatis的SqlSessionFactory
     */
    public static void initSqlSessionFactory(Set<Class<?>> mappers) {
        DataSource dataSource = DataBaseSource.getDataSource();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.setLogImpl(MybatisLog.class);
        TypeAliasRegistry typeAliasRegistry = configuration.getTypeAliasRegistry();
        mappers.forEach(mapper -> {
            typeAliasRegistry.registerAlias(mapper.getSimpleName(), mapper);
            configuration.addMapper(mapper);
        });
        FACTORY = new SqlSessionFactoryBuilder().build(configuration);
    }
}
